package com.nova.android.tvlauncher.ui.activity

import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import androidx.lifecycle.lifecycleScope
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.bean.atv_bean.HomeChannelDto
import com.nova.android.tvlauncher.bean.atv_bean.HomeProgramDto
import com.nova.android.tvlauncher.databinding.ActivityMainBinding
import com.nova.android.tvlauncher.ext.launchCommonPanelAtvActivity
import com.nova.android.tvlauncher.interfaces.factory.MainManagerFactory
import com.nova.android.tvlauncher.ui.activity.atv.CommonPanelActivity
import com.nova.android.tvlauncher.ui.receiver.AppStateChangeReceiver
import com.nova.android.tvlauncher.ui.receiver.NetworkChangeReceiver
import com.nova.android.tvlauncher.ui.view.ad.AdManagerImpl
import com.nova.android.tvlauncher.ui.viewmodel.MainViewModel
import com.nova.android.tvlauncher.utils.TvRepository
import com_github_lib_base.base.BaseVMActivity
import com_github_lib_base.ext.jsonToString
import com_github_lib_base.ext.replaceFragment
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MainActivity : BaseVMActivity<ActivityMainBinding, MainViewModel>() {

    override fun initBeforeContent() {
        hookWebView()
    }

    override fun initView() {
        registBroadcast()
        AdManagerImpl.init()
        replaceFragment(MainManagerFactory.mainManager.getMainFragment(), R.id.container)
        timelyDetectNewVersion()
        //testCache()
    }

    private fun checkNewVersion() {
        mViewModel.checkVersionUpdate { updateDto ->
            if (updateDto != null) {
                if (!updateDto.downLink.isNullOrEmpty()) {
                    //非强制更新
                    AppCache.updateInfo = updateDto.jsonToString()
                    CommonPanelActivity.UPDATE_APP.launchCommonPanelAtvActivity()
                }
            } else {
                //请求失败
            }
        }
    }

    private fun timelyDetectNewVersion() {
        lifecycleScope.launch {
            while (true) {
                delay(30000)
                checkNewVersion()
                delay(24 * 60 * 60 * 1000L) // 延迟 24 小时
            }
        }

    }


    private var receiver: AppStateChangeReceiver? = null
    lateinit var networkChangeReceiver: NetworkChangeReceiver
    private var isRegistered = false
    private fun registBroadcast() {
        if (!isRegistered) {
            networkChangeReceiver = NetworkChangeReceiver()
            val netFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
            registerReceiver(networkChangeReceiver, netFilter)

            receiver = AppStateChangeReceiver()
            val filter = IntentFilter()
            filter.addAction(Intent.ACTION_PACKAGE_ADDED)
            filter.addAction(Intent.ACTION_PACKAGE_REMOVED)
            filter.addAction(Intent.ACTION_PACKAGE_REPLACED)
            filter.addDataScheme("package")
            registerReceiver(receiver, filter)


            isRegistered = true
        }
    }

    private fun unregisterReceiver() {
        if (isRegistered) {
            unregisterReceiver(networkChangeReceiver)
            unregisterReceiver(receiver)
            isRegistered = false
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver()
    }

    private fun testCache() {
        val list = TvRepository.getChannels()
        val channelList = mutableListOf<HomeChannelDto>()
        list.forEach {
            val programList = TvRepository.getPreviewPrograms(it.id)
            if (programList.isNotEmpty()) {
                val channelId = it.fields.get("_id") as Long
                val channelName = it.fields.get("display_name") as String
                val packageName = it.fields.get("package_name") as String
                val intentUrl = it.fields.get("app_link_intent_uri") as String
                val homeChannelDto = HomeChannelDto()
                homeChannelDto.channelId = channelId
                homeChannelDto.channelName = channelName.toString()
                homeChannelDto.packageName = packageName.toString()
                homeChannelDto.intentUrl = intentUrl.toString()
                val list = mutableListOf<HomeProgramDto>()
                programList.forEach {
                    val programId = it.fields.get("_id") as Long
                    val programTitle = it.fields.get("title") as String
                    val programDesc = it.fields.get("short_description") as String
                    val programCover = it.fields.get("poster_art_uri") as String
                    val programIntentUrl = it.fields.get("intent_uri") as String
                    val programDto = HomeProgramDto()
                    programDto.programId = programId
                    programDto.programTitle = programTitle.toString()
                    programDto.programDesc = programDesc.toString()
                    programDto.programCover = programCover.toString()
                    programDto.intentUrl = programIntentUrl.toString()
                    list.add(programDto)
                }
                homeChannelDto.programList = list
                channelList.add(homeChannelDto)
            }
        }
        //TvRepository(this).getPreviewPrograms()
        //firstRun()
        //secondRun()
    }

    override fun onBackPressed() {

    }
}